<?php
declare (strict_types = 1);
namespace app\mall\model;
use app\order\model\Order;
use app\order\model\OrderGoods;
use app\user\model\User;
use think\Model;

use app\common\model\BaseModel;
use app\common\self\MyJob;

Class GoodsComment extends BaseModel
{
    public $limit = 2;
    public $field = 'id,uid,level,discuss,reply,cover,add_time,sort,is_anonymous';

    public function getDiscussAttr($value){
        return emojiDecode($value);
    }

    public function getReplyAttr($value){
        return emojiDecode($value);
    }

    //    预处理数据处理 轮播图
    public function getCoverAttr($value)
    {
        //return env('app.host_domin').'://'.$_SERVER['HTTP_HOST'].$value;
        if(!$value) return [];
        $arrs = $value ? explode(',',$value) : [];
        if($arrs && is_array($arrs) && count($arrs) > 0){
            $all = [];
            foreach($arrs as $i){
//                $all[] = env('app.host_domin').'://'.env('app.static_host').$i;
                if(checkFile($value))
                    $all[] =  getApiDominUrl($i);
                else
                    $all[] = getHostDominUrl($i);
            }
            return $all;
        }
//        return [env('app.host_domin').'://'.env('app.static_host').$value];
        return [checkFile($value) ? getApiDominUrl($value) : getHostDominUrl($value)];
    }


    // 商城-获取商品数据
    public function getList($get)
    {
        $prefix_order = '';
        if(isset($get['limit']) && $get['limit'] == 2){
            $prefix_order = 'sort desc,';
        }
        $oredr = $prefix_order.'add_time desc';
        $goods_id = isset($get['goods_id']) ? $get['goods_id'] : 0;
        if(!$goods_id || $goods_id <= 0)
            return retu_json(400,'商品id必须有');
        $where = ['goods_id'=>$goods_id,'is_display'=>1,'is_delete'=>0];
        // 排序
        if(isset($get['orderKey']) && in_array($get['orderKey'],['sales_volume','default_discount_price','add_time']))
            $oredr = $get['orderKey']." ".(isset($get['order']) && in_array($get['order'],['desc','asc']) ? $get['order'] : 'desc');
        $this->queryList($get,$this->field,$where,$oredr);
        if($this->modelList){
            // 迭代  模型数组
            foreach($this->modelList as $k => $item){
                $this->list['data'][$k]['nickname'] = '匿名用户';
                $this->list['data'][$k]['avatarurl'] = 'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/icon/%E7%BC%96%E7%BB%84%205%402x.png';
                // 如果是匿名用户
                if($item->is_anonymous == 0 && $item->getUserModel){
                    // 拿取到用户名和用户头像地址
                    $this->list['data'][$k]['nickname'] = $item->getUserModel->nickname;
                    $this->list['data'][$k]['nickname'] = $item->getUserModel ? $item->getUserModel : '匿名用户';
                    if($item->getUserModel->nickname != '匿名用户'){
                        $this->list['data'][$k]['nickname'] = substr_cut($item->getUserModel->nickname);
                    }
                    $this->list['data'][$k]['avatarurl'] = $item->getUserModel->avatarurl;
                }
            }
        }
    }

    /**
     * 添加商品评论
     */
    public function add($request,$user)
    {
        $id = $request->param('id',0);
        if(!$id || $id <= 0)
            return retu_json(400,'id不得为空');
        if(!Goods::where('id',$id)->count())
            return retu_json(400,'没有该商品记录');
        $level = $request->param('level',0);
        if(!$level || $level <= 0)
            return retu_json(400,'评分不得为空');
        $discuss = $request->param('discuss',0);
        if(!$discuss || strlen($discuss) <= 6)
            return retu_json(400,'评论内容不得小于6个文字');
        if(strlen($discuss) > 200)
            return retu_json(400,'评论字数不得超过200字符');
        $cover = $request->param('cover','');

        // 看此处是否需要无限次评论
        /*
        $order_goods_id = $request->get('order_goods_id',0);
        if(!$order_goods_id || $order_goods_id <= 0)
            return retu_json(400,'订单-商品不得为空');
        if(!$order_goods_idModel = OrderGoods::find($order_goods_id))
            return retu_json(400,'订单-商品没有改记录');
        if($order_goods_idModel->is_appraise== 1)
            return retu_json(400,'订单-商品已评论过');
        */

        $oid = $request->param('oid',-1);
        if(!$oid || $oid <= 0)
            return retu_json(400,'订单id不得为空');
        $orderOne = Order::where(['id'=>$oid,'uid'=>$user->id])->find();
        if(!$orderOne)
            return retu_json(400,'没有该订单号');
        
        // 如果存在图片
        if($cover && strlen($cover) > 10){
            $imgs = explode(',',$cover);
            $imgs_str = '';$len = count($imgs);
            $date = date('Y_m_d');
            $prefix_url = config('cos.prefix_url');
            $d = app()->getRootPath().'public/';
            $lastData = [];
            foreach($imgs as $k => $v){
                if(!$v) continue;
                $dir = explode('/',$v);
                $cos_name = '/newUploads/api_goods_comment/'.$date.'/'.$dir[3];
                $queue_data = ['file'=>$d.$v,'cos_path' => $cos_name];
                // 不是最后一个
                if($k != $len - 1){
                    $imgs_str .=     $prefix_url.$cos_name.',';
                    MyJob::pushQueue('FileUploadsJob',$queue_data,2);
                }else{
                    $imgs_str .=     $prefix_url.$cos_name;
                    $queue_data['table'] = serialize($this);
                    $queue_data['data'] = ['cover' => $imgs_str];
                    $lastData = $queue_data;
                }
            }
            if($imgs_str && strlen($imgs_str) > 10)
                $cover = $imgs_str;
        }

        $newId = $this->insertGetId([
            'goods_id'=> $id,
            'uid' => $user->id,
            'cover' => $cover,
            'level' => $level,
            'discuss'=>$discuss,
            'is_interior' => 1, // 不是内部评论
            'add_time' => time(),
            'is_display' => 0,
            'oid' => $oid
        ]);
        if($newId > 0 && isset($lastData) && count($lastData) > 0 && is_array($lastData)){
            $lastData['id'] = $newId;
            MyJob::pushQueue('FileUploadsJob',$lastData,2);
        }
        Order::where(['id'=>$oid,'uid'=>$user->id])->update([
           'is_appraise' => 1
        ]);
        if(!$newId)
            return retu_json(400,'评论失败');
        return $newId;
    }

    /**
     * 一对一关联
     * @return \think\model\relation\HasOne  返回关联当前用户user模型
     */
    public function getUserModel()
    {
        // 关联的用户表  用户表id,   当前字段
        return $this->hasOne(User::class,'id','uid');
    }

    /**
     * 一对一关联
     * @return \think\model\relation\HasOne  返回关联当前商品模型
     */
    public function getGoodsModel()
    {
        // 关联的商品表  商品表id,   当前字段
        return $this->hasOne(Goods::class,'id','goods_id');
    }
}